<template>
  <div class="customerAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <!-- v-if="!contactAddShow" 保存不隐藏 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(customerFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-show="!contactAddShow"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType !== "detail"
                ? pageType === "add"
                  ? "新增"
                  : "编辑"
                : ""
            }}客户信息</span
          >
        </template>
        <div class="customer-info">
          <el-form
            :model="customerForm"
            ref="customerFormRef"
            :rules="queryRules"
            label-width="100px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="业务部门：" prop="deptId">
                  <!-- <el-select
                    ref="refSelect"
                    v-model="customerForm.deptId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleDepart"
                  >
                    <el-option
                      v-for="dict in deptList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select> -->
                  <el-tree-select
                    ref="refSelect"
                    class="search-input"
                    style="height: 100%"
                    v-model="customerForm.deptId"
                    :data="deptList"
                    :props="{
                      value: 'deptId',
                      label: 'deptName',
                      children: 'children',
                    }"
                    value-key="deptId"
                    placeholder="请选择"
                    check-strictly
                    clearable
                    :render-after-expand="false"
                    @change="handleDepart"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="业务人员：" prop="userId">
                  <el-select
                    v-model="customerForm.userId"
                    placeholder="请选择"
                    clearable
                    filterable
                    popper-class="custom-dropdown"
                    class="search-select"
                  >
                    <!-- <el-option
                      v-for="dict in userList"
                      :key="dict.userId"
                      :label="dict.nickName"
                      :value="dict.userId"
                    /> -->
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >人员姓名</span
                      >
                      <span style="margin: 0 90px 0 57px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickName"
                        :value="item.userId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.nickName }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{
                            item.phonenumber ? item.phonenumber : "--"
                          }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            font-size: 13px;
                            margin: 0 0px 0 0px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.postName ? item.postName : "--" }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.deptName ? item.deptName : "--" }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户名称：" label-width="100" prop="name">
                  <el-input
                    v-model="customerForm.name"
                    placeholder="请输入"
                    clearable
                    maxlength="20"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="企业法人："
                  label-width="150"
                  prop="legalPerson"
                >
                  <el-input
                    v-model="customerForm.legalPerson"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="单位地址：" prop="region">
                  <!-- <el-cascader
                    v-model="currentChoose"
                    v-bind="_options"
                    :options="addressList"
                    :disabled="_options.disabled"
                    @change="handleChange"
                  /> -->
                  <el-cascader
                    class="search-input"
                    v-model="customerForm.region"
                    :options="provincesList"
                    @change="handlerregion"
                    :props="{
                      value: 'id',
                      label: 'name',
                      children: 'children',
                    }"
                    clearable
                  />
                  <!-- @change="handleCascader" -->
                  <!-- <el-select
                    filterable
                    style="width: 93px"
                    v-model="customerForm.province"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleProvince('province')"
                  >
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 93px; margin: 0 5px"
                    v-model="customerForm.city"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleProvince('city')"
                  >
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 93px"
                    v-model="customerForm.area"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="详细地址："
                  prop="customerAddress"
                  label-width="100"
                >
                  <el-input
                    style="width: 100%"
                    v-model="customerForm.customerAddress"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="社会统一信用代码："
                  label-width="150"
                  prop="uscc"
                >
                  <el-input
                    v-model="customerForm.uscc"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="国标行业：" prop="industry">
                  <el-select
                    v-model="customerForm.industry"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in industryList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 添加联系人 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        v-if="contactAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">{{
            operateType !== "edit" ? "添加联系人" : "编辑联系人"
          }}</span>
        </template>
        <div class="customer-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="100px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="姓名：" prop="name">
                  <el-input
                    ref="refInput"
                    v-model="contactForm.name"
                    placeholder="请输入"
                    clearable
                    maxlength="10"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系方式：" prop="phone">
                  <el-input
                    v-model="contactForm.phone"
                    placeholder="请输入"
                    clearable
                    maxlength="11"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="角色："
                  prop="contactRole"
                  label-width="100px"
                >
                  <el-select
                    v-model="contactForm.contactRole"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleContactType"
                  >
                    <el-option
                      v-for="dict in contactTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职位：" prop="position" label-width="120">
                  <el-input
                    v-model="contactForm.position"
                    placeholder="请输入"
                    clearable
                    maxlength="10"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="微信：">
                  <el-input
                    v-model="contactForm.wechat"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="生日：">
                  <!-- <el-input
                    v-model="contactForm.birthday"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  /> -->
                  <el-date-picker
                    v-model="contactForm.birthday"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="爱好：" label-width="100px">
                  <el-input
                    v-model="contactForm.hobby"
                    placeholder="请输入"
                    clearable
                    maxlength="40"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="家庭地址：" label-width="120">
                  <el-input
                    v-model="contactForm.address"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="客户备注：" prop="remarks">
                  <el-input
                    v-model="contactForm.remarks"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                    maxlength="30"
                    @keyup.enter.stop="handleContactAdd(contactFormRef)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 联系人列表 -->
      <el-collapse-item
        name="3"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">联系人列表</span>
          <div
            v-if="pageType !== 'detail' && !contactAddShow"
            class="nofixed-search-button button-position"
          >
            <el-button class="btn add" @click.stop="handleContactOperate"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleCustomerBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="customerForm.customerContactInfos"
            border
            :height="
              pageType === 'detail'
                ? '100%'
                : contactAddShow
                ? '380px'
                : '380px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="姓名"
              prop="name"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="联系方式"
              prop="phone"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="角色"
              prop="contactRoleName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="职位"
              prop="position"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="微信"
              prop="wechat"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="生日"
              prop="birthday"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="爱好"
              prop="hobby"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="家庭地址"
              prop="address"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="备注"
              prop="remarks"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-dialog
      :title="operateType !== 'edit' ? '添加联系人' : '编辑联系人'"
      v-model="operateDialogShow"
      style="margin-top: 20vh !important"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :close="handleCustomerBack"
    >
      <div>
        <el-form
          :model="contactForm"
          ref="contactFormRef"
          :rules="queryContactRules"
          label-width="100px"
          v-enterToNext
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="姓名：" prop="name">
                <el-input
                  ref="refInput"
                  v-model="contactForm.name"
                  placeholder="请输入"
                  clearable
                  maxlength="10"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式：" prop="phone">
                <el-input
                  v-model="contactForm.phone"
                  placeholder="请输入"
                  clearable
                  maxlength="11"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="角色："
                prop="contactRole"
                label-width="100px"
              >
                <el-select
                  v-model="contactForm.contactRole"
                  placeholder="请选择"
                  clearable
                  class="search-select"
                  @change="handleContactType"
                >
                  <el-option
                    v-for="dict in contactTypeList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职位：" prop="position" label-width="120">
                <el-input
                  v-model="contactForm.position"
                  placeholder="请输入"
                  clearable
                  maxlength="10"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="6">
              <el-form-item label="微信：">
                <el-input
                  v-model="contactForm.wechat"
                  placeholder="请输入"
                  clearable
                  maxlength="30"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生日：">
                <!-- <el-input
                    v-model="contactForm.birthday"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  /> -->
                <el-date-picker
                  v-model="contactForm.birthday"
                  format="YYYY/MM/DD"
                  class="search-input"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="爱好：" label-width="100px">
                <el-input
                  v-model="contactForm.hobby"
                  placeholder="请输入"
                  clearable
                  maxlength="40"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="家庭地址：" label-width="120">
                <el-input
                  v-model="contactForm.address"
                  placeholder="请输入"
                  clearable
                  maxlength="30"
                  class="search-input"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="客户备注：" prop="remarks">
                <el-input
                  v-model="contactForm.remarks"
                  placeholder="请输入"
                  clearable
                  class="search-input"
                  maxlength="30"
                  @keyup.enter.stop="handleContactAdd(contactFormRef)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <!--  class="customer-info" -->

        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="handleContactAdd(contactFormRef)"
            >保存</el-button
          >

          <el-button
            style="background-color: #fff"
            @click="handleCustomerBack()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getProvinceApi,
  getUserListApi,
  getnewDeptListApi,
  addCustomerApi,
  editCustomerApi,
  getCustomerDetailApi,
} from "@/api/information/customer";
import { getProvincesList } from "@/api/pub";
const { proxy } = getCurrentInstance();
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 客户新增组件显隐
  "customerAddShow",
  // 更新客户新增组件显隐
  "update:customerAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const customerFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("add");
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 新增编辑弹窗显隐
const operateDialogShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
//联系人模块标题文字
const contacts = ref("添加联系人");
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 省市区列表
const provincesList = ref([]);

//省市区校验规则
// const provinceValidate = (rule, value, callback) => {
//   const { province, city, area } = customerForm.value;
//   if (!province || !city || !area) {
//     callback(new Error("请选择省市区"));
//   } else {
//     callback();
//   }
// };

// 客户表单数据模板
const customerFormTemplate = {
  deptId: "",
  customerAddress: "",
  area: null,
  city: null,
  uscc: "",
  updateUser: null,
  industry: null,
  userId: null,
  province: null,
  legalPerson: "",
  name: "",
  createUser: null,
  customerContactInfos: [],
  remarks: "",
  region: [],
};
// 联系人表单数据模板
const contactFormTemplate = {
  name: "",
  contactRoleName: "",
  birthday: "",
  address: "",
  contactId: null,
  phone: "",
  wechat: "",
  customerId: null,
  contactRole: null,
  position: "",
  remarks: "",
  hobby: "",
};
const data = reactive({
  // 客户表单
  customerForm: JSON.parse(JSON.stringify(customerFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    deptId: [{ required: true, message: "请选择业务部门", trigger: "change" }],
    userId: [{ required: true, message: "请选择业务人员", trigger: "change" }],
    name: [
      { required: true, message: "请输入客户名称", trigger: "blur" },
      { min: 1, max: 19, message: "最多可输入20字", trigger: "blur" },
    ],
    legalPerson: [
      { required: true, message: "请输入企业法人", trigger: "blur" },
      { min: 1, max: 10, message: "最多可输入10字", trigger: "blur" },
    ],
    customerAddress: [
      { required: true, message: "请输入详细地址", trigger: "blur" },
      { min: 1, max: 30, message: "最多可输入30字", trigger: "blur" },
    ],
    uscc: [
      { required: true, message: "请输入社会统一信用代码", trigger: "blur" },
      { min: 1, max: 40, message: "最多可输入40字", trigger: "blur" },
    ],
    industry: [
      { required: true, message: "请输入国标行业", trigger: "change" },
    ],

    area: [
      {
        required: true,
        message: "请选择省市区",
        trigger: "change",
      },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    name: [
      { required: true, message: "请输入姓名", trigger: "blur" },
      { min: 1, max: 15, message: "最多可输入15字", trigger: "blur" },
    ],
    phone: [
      { required: true, message: "请输入联系方式", trigger: "blur" },
      { min: 1, max: 11, message: "最多可输入11字", trigger: "blur" },
    ],
    contactRole: [{ required: true, message: "请选择角色", trigger: "change" }],
    position: [{ required: true, message: "请输入职位", trigger: "blur" }],
    remarks: [{ max: 29, message: "最多可输入30字", trigger: "blur" }],
  },
  // 角色列表
  contactTypeList: [],
  // 国标行业列表
  industryList: [],
  // // 省列表
  // provinceList: [],
  // // 市列表
  // cityList: [],
  // // 区列表
  // areaList: [],
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
});

const {
  customerForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
  deptList,
} = toRefs(data);

/**
 * @description: 保存
 * @param {Object} customerFormRef 客户表单引用
 */
const handleAddSave = async (customerFormRef) => {
  // if (!customerFormRef) return;
  if (customerForm.value.customerContactInfos.length == 0) {
    ElMessage.error("请添加联系人");
    return;
  }

  await customerFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res;
          if (!customerForm.value.customerId) {
            // 新增客户
            res = await addCustomerApi(customerForm.value);
          } else {
            // 编辑客户
            res = await editCustomerApi(customerForm.value);
          }
          if (res.code === 200) {
            emit("update:customerAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            customerForm.value = JSON.parse(
              JSON.stringify(customerFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("updateFollowAddShow", false);
    emit("update:customerAddShow", false);
    customerForm.value = JSON.parse(JSON.stringify(customerFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:customerAddShow", false);
        customerForm.value = JSON.parse(JSON.stringify(customerFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理角色选择
 * @param {Number} value 选择值
 */
const handleContactType = (value) => {
  contactForm.value.contactRoleName =
    contactTypeList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        operateType.value = "add";
        customerForm.value.customerContactInfos[tableIndex.value] = JSON.parse(
          JSON.stringify(contactForm.value)
        );
      } else {
        customerForm.value.customerContactInfos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      if (contactFormRef) {
        contactFormRef.resetFields();
      }
      // nextTick(() => {
      //   refInput.value.focus();
      // });
      operateDialogShow.value = false;
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  // contactAddShow.value = true;
  operateDialogShow.value = true;
  operateType.value = "add";
  setTimeout(() => {
    refInput.value.focus();
  }, 500);
};

/**
 * @description: 联系人返回
 */
const handleCustomerBack = () => {
  // contactAddShow.value = false;
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
  operateDialogShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    customerForm.value.province = value[0];
    customerForm.value.city = value[1];
    customerForm.value.area = value[2];
  } else {
    customerForm.value.region = [];
    customerForm.value.province = null;
    customerForm.value.city = null;
    customerForm.value.area = null;
  }
};

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      customerForm.value.city = null;
      customerForm.value.area = null;
      getProvinceApi(customerForm.value.province).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      break;
    case "city":
      areaList.value = [];
      customerForm.value.area = null;
      getProvinceApi(customerForm.value.city).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      break;
  }
};

/**
 * @description: 处理部门选择
 * @param {Number} value 当前值
 */
const handleDepart = async (value) => {
  customerForm.value.userId = null;
  if (value) {
    await getUserListApi(customerForm.value.deptId).then((res) => {
      if (res.length > 0) {
        userList.value = res;
      } else {
        userList.value = [];
      }
    });
  } else {
    userList.value = [];
  }
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (contactFormRef.value) {
    contactFormRef.value.resetFields();
  }
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    // contactAddShow.value = true;
    operateDialogShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    ElMessageBox.confirm("此操作将删除该联系人信息，是否继续？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
      type: "warning",
    })
      .then(async () => {
        customerForm.value.customerContactInfos.splice(tabIndex, 1);
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getCustomerDetailApi(id);
    let array = [];
    if (res.erpCustomers.area) {
      array = [
        res.erpCustomers.province,
        res.erpCustomers.city,
        res.erpCustomers.area,
      ];
    }
    customerForm.value = {
      ...res.erpCustomers,
      customerContactInfos: res.erpCustomerContacts,
      region: array,
    };
    await getUserListApi(customerForm.value.deptId).then((res) => {
      if (res.length > 0) {
        userList.value = res;
      }
    });
    await getProvinceApi(customerForm.value.province).then((res) => {
      if (res.code === 200) {
        cityList.value = res.data;
      }
    });
    await getProvinceApi(customerForm.value.city).then((res) => {
      if (res.code === 200) {
        areaList.value = res.data;
      }
    });
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getProvincesList().then((res) => {
    if (res.code == 200) {
      provincesList.value = res.data;
    }
  });
  // 角色列表
  await getDictsApi("erp_contact_type").then((res) => {
    if (res.code === 200) {
      contactTypeList.value = res.data;
    }
  });
  // 国标行业列表
  await getDictsApi("erp_customer_industry").then((res) => {
    if (res.code === 200) {
      industryList.value = res.data;
    }
  });

  // 销售部门列表
  await getnewDeptListApi().then((res) => {
    if (res.code === 200) {
      deptList.value = proxy.handleTree(res.data, "deptId");
      // deptList.value = res.data;
      nextTick(() => {
        refSelect.value.focus(); // 聚焦
      });
    }
  });

  // // 省列表
  // await getProvinceApi(1).then((res) => {
  //   if (res.code === 200) {
  //     provinceList.value = res.data;
  //   }
  // });
}

onMounted(() => {
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.customerAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .customer-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
}
</style>

<style>
.custom-dropdown .dropdown-slot {
  height: 28px;
  line-height: 28px;
}

.custom-dropdown .scrollable-options {
  max-height: 200px; /* 根据需要设置合适的高度 */
  overflow-y: auto;
}
</style>
